<?php
/**
 * Created by PhpStorm.
 * User: 11893
 * Date: 2018/10/18
 * Time: 17:04
 */

namespace App\Utils;

class Lock
{
    protected $prefix = 'lock_';
    protected $expire = 5;
    protected $target;
    protected $result;

    public function prefix($prefix = '')
    {
        $this->prefix = $prefix;
        return $this;
    }

    public function expire($expire = 5)
    {
        $this->expire = $expire;
        return $this;
    }

    public function set($target)
    {
        $this->target = $target;
        $status = true;
        $key = $this->prefix . $target;
        $lockValue = time() + $this->expire;
        while ($status) {
            if (\Redis::setNx($key, $lockValue) || (\Redis::get($key) < time() && \Redis::getSet($key, $lockValue) < time())) {
                    $status = false;
                    \Redis::expire($key, $this->expire);
            } else {
                usleep(100);
            }
        }
        return $this;
    }

    public function work(\Closure $closure)
    {
        $this->result = $closure();
        return $this;
    }

    public function remove()
    {
        $key = $this->prefix.$this->target;
        if (\Redis::ttl($key)) {
            \Redis::del($key);
        }
    }

    public function getResult()
    {
        return $this->result;
    }
}